/**
 * Created by bianlian on 16/9/19.
 */

import React, { Component, PropTypes } from 'react';
import {
    AppRegistry,
    StyleSheet,
    View,
    ListView,
    Text,
    Image,
    TouchableOpacity,
    TouchableHighlight,
    BackAndroid,
    Platform,
    Switch,
    Alert
} from 'react-native';
import {connect} from 'react-redux';
const EntityLabels = require('../constants/entities');
import { MtContainer, MtSeparator, MtChar, MtColor, MtActionButton, MtToast } from 'martian-ui';
const MtIcon = require('martian-icon');
const { MtT7 } = MtChar;

import YaguanRoomDevices from '../container/YaguanRoomDevices';
import {fetchHouseList, fetchRoomList} from '../action/girlAction';
import Dimensions from 'Dimensions';
const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height / 2;
import { modelToKeyString, modelToComponet } from '../utils/modelToKeyString';

var jsonToNomarl = {
    "Switch": "switch",
    "Switch_1": "switch1",
    "Switch_2": "switch2",
    "Switch_3": "switch3",
};
class DeviceCell extends Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            value: false,
            isUpdata: false,
        };

    }

    /**
     * 调用数据 :
     *      1. 当触发Action方法请求数据反馈到Reducer中
     *      2. Reducer通过ActionType判断该更新哪个UI中的State
     *      3. 最后刷新界面显示数据
     */
    componentWillMount() {


        if (Platform.OS === 'android') {
            BackAndroid.addEventListener('hardwareBackPress', () => this.onBackAndroid());
        }
    }

    componentDidMount() {
        if (Platform.OS === 'android') {
            BackAndroid.addEventListener('hardwareBackPress', () => this.onBackAndroid());
        }
    }


    /**
     * 监听Android返回按键
     * @returns {boolean}
     */
    onBackAndroid() {

        const {navigator} = this.props;
        if (navigator.getCurrentRoutes().length > 1) {
            navigator.pop();
            return true;
        }
        //退出
        return false;

    }



    render() {
        const { device, rightShowType, addDeviceId, removeDeviceId, setValue, update, navigator, setParams, actions  } = this.props;
        const {isUpdata} = this.state;
        const { name, model, deviceId } = device || {};
        let RightView;

        if (rightShowType === 1){
            if(model && model.indexOf("ARGRACE_LIVING_WALLSWITCH")>=0){
                if (update) {
                    const key_string = modelToKeyString(model);
                    if (device[jsonToNomarl[key_string]] === '1'){
                        console.warn(1)

                    }else if (device[jsonToNomarl[key_string]] === '0'){
                        console.warn(0)
                        //this.setState({ value: false})
                    }
                    RightView= (
                        <View style={styles.buttonContainer}>
                            <Switch value={this.state.value}
                                    onTintColor='#00A5AD'
                                    onValueChange={(value)=>{

                                this.setState({ value})
                                setValue(value)

                            }}/>

                        </View>)
                }else {
                    RightView= (
                        <View style={styles.buttonContainer}>
                            <Switch value={this.state.value}
                                    onTintColor='#00A5AD'
                                    onValueChange={(value)=>{
                                this.setState({ value})
                                setValue(value)

                            }}/>

                        </View>)
                }

            }
            else {
                RightView = (
                    <TouchableOpacity
                        onPress={()=> {
                            if (modelToComponet(model) && modelToComponet(model) !== '' && model.indexOf("ARGRACE_LIVING_WALLSWITCH") < 0) {
                                navigator.push({
                                    component: modelToComponet(model),
                                    params: {
                                        navigator,
                                        deviceId,
                                        update: 'update',
										actions,
                                        setParams,
                                        isUpdate:(value)=>{
                                            this.setState({ isUpdata: value})
                                        }


                                    }
                                })
                            }

                        }}
                        style={{backgroundColor: '#fff', borderRadius: 10}}

                    >

                        <View
                            style={{
                                borderWidth: 2,
                                borderColor:  isUpdata ? '#D6D6D6' : '#24A7AC',
                                borderRadius: 10,
                                width: 60,
                                justifyContent: 'center',
                                alignItems: 'center',
                                height: 30,
                            }}
                        >
                            <MtT7 style={{

                                color: '#24A7AC',
                            }}>
                                {isUpdata ? '已设置' : '设置'}
                            </MtT7>
                        </View>
                    </TouchableOpacity>
                )
            }
        } else if (rightShowType === 2){
            RightView= (
                <TouchableOpacity
                    onPress={()=>{
                        addDeviceId(device.deviceId);

                    }}
                    style={{ backgroundColor: '#fff', borderRadius:10}}

                >
                    <View
                        style={{
                            borderRadius:10,
                            backgroundColor: '#3DB8C2',
                            width: 60,
                            justifyContent: 'center',
                            alignItems: 'center',
                            height: 30,
                        }}
                    >
                        <MtT7 style={{

                            color: '#fff',
                        }}>
                            添加
                        </MtT7>
                    </View>
                </TouchableOpacity>
            )
        } else if(rightShowType === 3){
            RightView= (

                <View style ={{ flexDirection: 'row',   alignItems: 'center',}}>
                    <MtT7 style={{
                        marginRight: 10,
                        color: '#D6D6D6',
                    }}>
                        已添加
                    </MtT7>
                    <TouchableOpacity
                        onPress={()=>{
                            removeDeviceId(device.deviceId);

                        }}
                        style={{ backgroundColor: '#fff', borderRadius:10}}

                    >
                        <View
                            style={{
                                borderWidth:2,
                                borderColor:'#D6D6D6',
                                borderRadius:10,
                                width: 60,
                                justifyContent: 'center',
                                alignItems: 'center',
                                height: 30,
                            }}
                        >
                            <MtT7 style={{

                                color: '#D6D6D6',
                            }}>
                                移除
                            </MtT7>
                        </View>
                    </TouchableOpacity>
                </View>
            )
        }

        return (
            <View style={styles.rowContainer}>
                <View style={styles.favItem}>
                    <MtIcon
                        name="fav-solid"
                        size={30}
                        color={MtColor.main}
                    />
                    <MtT7 style={{ marginLeft: 3}}>
                        {name}
                    </MtT7>

                </View>
                {RightView}
            </View>
        );
    }



}

function mappingStateToProps(state, ownProps) {

    const { deviceId } = ownProps;
    console.warn(deviceId)
    const entities= state['entities'];
    const devicesEntities = entities[EntityLabels.devices];
    const device = devicesEntities && devicesEntities[deviceId];
    return {
        device
    }
}


module.exports = connect(mappingStateToProps)(DeviceCell);
const styles = StyleSheet.create({
    rowContainer: {
        backgroundColor: 'white',
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 15,
        paddingHorizontal: 10,
        flexDirection:'row',
        flex: 1
    },
    tagInner: {
        alignItems: 'flex-end',
        height: 55,
        justifyContent: 'center',
    },
    tagColorBox: {
        height: 26,
        paddingHorizontal: 10,
        justifyContent: 'center',
        alignItems: 'center',
    },
    separator: {
        paddingHorizontal: 15,
    },
    favItem: {
        flex: 1,
        height: 50,
        paddingHorizontal: 15,
        flexDirection: 'row',
        alignItems: 'center',
    },
    buttonContainer: {
        flex: 1,
        marginRight: 10,
        marginBottom: 15,
        alignItems: 'flex-end',
    },
});
